"use strict";
$jq.namespace('PeopleMedia.CP');

PeopleMedia.CP.RegistrationManager = function () {
    this._siteId = null;
    this._emailGUID = "";
    this._registrationButtonFieldname = "btnRegister";
    this._registrationProcess = null;
    this._onRegistrationSuccess = null;
    this._onRegistrationFailure = null;
    this._registrationPanelId = "divRegistration";
    this._usernameFieldname = "txtUsername";
    this._passwordFieldname = "txtPassword";
    this._emailAddressFieldname = "txtEmailAddress";
    this._emailAddressConfirmationFieldname = "txtEmailAddressConfirmation";
    this._countryCodeFieldname = "ddlCountry";
    this._postalCodeFieldname = "txtPostalCode";
    this._postalCodeDivFieldname = "divPostalCode";
    this._cityFieldname = "txtCity";
    this._stateFieldname = "txtState";
    this._cityStateDivFieldname = "divCityState";
    this._genderFieldname = "ddlGender";
    this._genderSeekFieldname = "ddlGenderSeek";
    this._genderCombinedFieldname = "ddlGenderCombined";
    this._birthMonthFieldname = "ddlBirthMonth";
    this._birthDayFieldname = "ddlBirthDay";
    this._birthYearFieldname = "ddlBirthYear";
    this._termsAndConditionsClassname = "chkTermsAndConditions";
    this._adOptInClassname = "chkadOptIn";
    this._surveyAnswerFieldname = "ddlSurveyAnswer";
    this._memberId = null;
    this._registrationData = null;
    this._panelCount = 1;
    this._questions = [];
    this._currentPanelNumber = 1;
    this._onQuestionDisplay = null;
    this._originalEmailAddress = "";
};

PeopleMedia.CP.RegistrationManager.prototype = {
    Oid: "PeopleMedia.CP.RegistrationManager-v1.3",
    SiteId: function (siteId) {
        if (arguments.length > 0) {
            this._siteId = siteId;
        } else {
            return this._siteId;
        }
    },
    EmailGUID: function (emailGUID) {
        if (arguments.length > 0) {
            this._emailGUID = emailGUID;
        } else {
            return this._emailGUID;
        }
    },
    RegistrationButtonFieldname: function (name) {
        if (arguments.length > 0) {
            this._registrationButtonFieldname = name;
        } else {
            return this._registrationButtonFieldname;
        }
    },
    RegistrationProcess: function (process) {
        if (arguments.length > 0) {
            this._registrationProcess = process;
        } else {
            return this._registrationProcess;
        }
    },
    OnRegistrationSuccess: function (onRegistrationSuccess) {
        if (arguments.length > 0) {
            this._onRegistrationSuccess = onRegistrationSuccess;
        } else {
            return this._onRegistrationSuccess;
        }
    },
    OnRegistrationFailure: function (onRegistrationFailure) {
        if (arguments.length > 0) {
            this._onRegistrationFailure = onRegistrationFailure;
        } else {
            return this._onRegistrationFailure;
        }
    },
    RegistrationPanelId: function (registrationPanelId) {
        if (arguments.length > 0) {
            this._registrationPanelId = registrationPanelId;
        } else {
            return this._registrationPanelId;
        }
    },
    RegistrationPanel: function (registrationPanel) {
        return $jq("#" + this.RegistrationPanelId());
    },
    UsernameFieldname: function (name) {
        if (arguments.length > 0) {
            this._usernameFieldname = name;
        } else {
            return this._usernameFieldname;
        }
    },
    Username: function () {
        return $jq("#" + this.UsernameFieldname()).val();
    },
    PasswordFieldname: function (name) {
        if (arguments.length > 0) {
            this._passwordFieldname = name;
        } else {
            return this._passwordFieldname;
        }
    },
    Password: function () {
        return $jq("#" + this.PasswordFieldname()).val();
    },
    EmailAddressFieldname: function (name) {
        if (arguments.length > 0) {
            this._emailAddressFieldname = name;
        } else {
            return this._emailAddressFieldname;
        }
    },
    EmailAddress: function () {
        return $jq("#" + this.EmailAddressFieldname()).val();
    },
    OriginalEmailAddress: function () {
        if (arguments.length > 0) {
            this._originalEmailAddress = name;
        } else {
            return this._originalEmailAddress;
        }
    },
    EmailAddressConfirmationFieldname: function () {
        if (arguments.length > 0) {
            this._emailAddressConfirmationFieldname = name;
        } else {
            return this._emailAddressConfirmationFieldname;
        }
    },
    EmailAddressConfirmation: function () {
        return $jq("#" + this.EmailAddressConfirmationFieldname()).val();
    },
    CountryCodeFieldname: function (name) {
        if (arguments.length > 0) {
            this._countryCodeFieldname = name;
        } else {
            return this._countryCodeFieldname;
        }
    },
    CountryCode: function () {
        return $jq("#" + this.CountryCodeFieldname()).val();
    },
    PostalCodeFieldname: function (name) {
        if (arguments.length > 0) {
            this._postalCodeFieldname = name;
        } else {
            return this._postalCodeFieldname;
        }
    },
    PostalCode: function () {
        return $jq("#" + this.PostalCodeFieldname()).val();
    },
    PostalCodeDivFieldname: function (name) {
        if (arguments.length > 0) {
            this._postalCodeDivFieldname = name;
        } else {
            return this._postalCodeDivFieldname;
        }
    },
    CityFieldname: function (name) {
        if (arguments.length > 0) {
            this._cityFieldname = name;
        } else {
            return this._cityFieldname;
        }
    },
    City: function () {
        return $jq("#" + this.CityFieldname()).val();
    },
    StateFieldname: function (name) {
        if (arguments.length > 0) {
            this._stateFieldname = name;
        } else {
            return this._stateFieldname;
        }
    },
    State: function () {
        return $jq("#" + this.StateFieldname()).val();
    },
    CityStateDivFieldname: function (name) {
        if (arguments.length > 0) {
            this._cityStateDivFieldname = name;
        } else {
            return this._cityStateDivFieldname;
        }
    },
    GenderFieldname: function (name) {
        if (arguments.length > 0) {
            this._genderFieldname = name;
        } else {
            return this._genderFieldname;
        }
    },
    Gender: function () {
        return $jq("#" + this.GenderFieldname()).val();
    },
    GenderSeekFieldname: function (name) {
        if (arguments.length > 0) {
            this._genderSeekFieldname = name;
        } else {
            return this._genderSeekFieldname;
        }
    },
    GenderSeek: function () {
        return $jq("#" + this.GenderSeekFieldname()).val();
    },
    GenderCombinedFieldname: function (name) {
        if (arguments.length > 0) {
            this._genderCombinedFieldname = name;
        } else {
            return this._genderCombinedFieldname;
        }
    },
    GenderCombined: function () {
        return $jq("#" + this.GenderCombinedFieldname()).val();
    },
    GenderCombinedSelf: function () {
        if (this.GenderCombined() != null && this.GenderCombined().length == 2) {
            return this.GenderCombined().substr(0, 1);
        }
        return "";
    },
    GenderCombinedSeeking: function () {
        if (this.GenderCombined() != null && this.GenderCombined().length == 2) {
            return this.GenderCombined().substr(1, 1);
        }
        return "";   
    },    
    BirthMonthFieldname: function (name) {
        if (arguments.length > 0) {
            this._birthMonthFieldname = name;
        } else {
            return this._birthMonthFieldname;
        }
    },
    BirthMonth: function () {
        return $jq("#" + this.BirthMonthFieldname()).val();
    },

    BirthDayFieldname: function (name) {
        if (arguments.length > 0) {
            this._birthDayFieldname = name;
        } else {
            return this._birthDayFieldname;
        }
    },
    BirthDay: function () {
        return $jq("#" + this.BirthDayFieldname()).val();
    },
    BirthYearFieldname: function (name) {
        if (arguments.length > 0) {
            this._birthYearFieldname = name;
        } else {
            return this._birthYearFieldname;
        }
    },
    BirthYear: function () {
        return $jq("#" + this.BirthYearFieldname()).val();
    },
    BirthDate: function () {
        var birthMonth = this.BirthMonth();
        var birthDay = this.BirthDay();
        var birthYear = this.BirthYear();
        return birthMonth + '/' + birthDay + '/' + birthYear;
    },
    SurveyAnswerFieldName: function (name) {
        if (arguments.length > 0) {
            this._surveyAnswerFieldname = name;
        } else {
            return this._surveyAnswerFieldname;
        }
    },
    SurveyAnswer: function () {
        if ($jq("#" + this.SurveyAnswerFieldName()).val() != undefined) {
            return $jq("#" + this.SurveyAnswerFieldName()).val();
        } else {
            return 0;
        }
    },
    TermsAndConditionsClassname: function (name) {
        if (arguments.length > 0) {
            this._termsAndConditionsClassname = name;
        } else {
            return this._termsAndConditionsClassname;
        }
    },
    TermsAndConditions: function () {
        return $jq("." + this.TermsAndConditionsClassname()).is(":checked");
    },
    AdOptInClassname: function (name) {
        if (arguments.length > 0) {
            this._adOptInClassname = name;
        } else {
            return this._adOptInClassname;
        }
    },
    AdOptIn: function () {
        if($jq("#" + this.AdOptInClassname()).is(":checked")) { 
            return true;
        } else {
            return false;
        }
    },
    MemberId: function (memberId) {
        if (arguments.length > 0) {
            this._memberId = memberId;
        } else {
            return this._memberId;
        }
    },
    RegistrationData: function () {
        return this._registrationData;
    },
    Questions: function () {
        return this._questions;
    },
    PanelCount: function (panelCount) {
        if (arguments.length > 0) {
            this._panelCount = panelCount;
        } else {
            return this._panelCount;
        }
    },
    CurrentPanelNumber: function (currentPanelNumber) {
        if (arguments.length > 0) {
            this._currentPanelNumber = currentPanelNumber;
        } else {
            return this._currentPanelNumber;
        }
    },
    OnQuestionDisplay: function (onQuestionDisplay) {
        if (arguments.length > 0) {
            this._onQuestionDisplay = onQuestionDisplay;
        } else {
            return this._onQuestionDisplay;
        }
    },
    initialize: function (currentQueryString) {
        try {
            this.SiteId(PeopleMedia.CP.SiteID());
            var keyValues = PeopleMedia.Net.getQueryString(currentQueryString);
            var emailGUID = PeopleMedia.Net.getQueryStringValue(keyValues, "EmailGUID");
            if (typeof (emailGUID) !== 'undefined' && emailGUID !== null && emailGUID.length == 36) {
                this.EmailGUID(emailGUID);
            }

            var thisObj = this;
            var regButtonName = this.RegistrationButtonFieldname();
            if (regButtonName != undefined && regButtonName != null && $jq('#' + regButtonName)) {
                $jq('#' + regButtonName).bind('click', function () {
                    thisObj.processRegistration();
                });
            }
            var emailText = this.EmailAddressFieldname();
            if (emailText != undefined && emailText != null && $jq('#' + emailText)) {
                $jq("#" + emailText).blur(function () {
                    thisObj.checkCommonEmailMistakes();
                });
            }
        

            var countrySelectName = this.CountryCodeFieldname();
            if (countrySelectName != undefined && countrySelectName != null && $jq('#' + countrySelectName).length > 0) {
                var geoMgr = new PeopleMedia.CP.GeoManager();
                geoMgr.loadDDL(countrySelectName);

                var postalCodeDivName = this.PostalCodeDivFieldname();
                var cityStateDivName = this.CityStateDivFieldname();

                if (postalCodeDivName != undefined && postalCodeDivName != null && cityStateDivName != undefined && cityStateDivName != null) {
                    this.addCountrySelectCityStatePostalCodeSwap(countrySelectName, postalCodeDivName, cityStateDivName);
                }

                // update zip/postal code labels based on us/canada selection
                $jq('#' + countrySelectName).bind('click', function () {
                    thisObj.updateZipPostalCodeLabel();
                });
            }

            this.loadBirthDateDropdowns();
            this.loadSurveyDDL();

           
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"initialize" });
        }
    },
    processRegistration: function () {
        try {
            var thisObj = this;
            var process = this.RegistrationProcess();
            if (process == undefined || process == null) {
                process = function () {
                    thisObj.standardRegistrationProcess();
                };
            }
            process();
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"processRegistration" });
        }
    },
    loadSurveyDDL: function () {
        try {

            if (this.SurveyAnswerFieldName() != undefined && this.SurveyAnswerFieldName() != null && $jq("#" + this.SurveyAnswerFieldName()).length > 0) {
                if ($jq("#" + this.SurveyAnswerFieldName())[0].length == 0) {
                    var answer = [
                        { id: "1", name: "Online Ad" },
                        { id: "2", name: "Article" },
                        { id: "3", name: "TV Commercial" },
                        { id: "4", name: "Word of Mouth" },
                        { id: "5", name: "Radio" },
                        { id: "6", name: "Other"}];

                    var defaultanswers = [{ id: "0", name: "Choose" }];

                    var answerarray = defaultanswers.concat(answer.sort(function () {
                        return 0.5 - Math.random();
                    }));

                    PeopleMedia.UI.loadDDL(this.SurveyAnswerFieldName(), answerarray, "id", "name");
                }
            }

        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"loadSurveyDDL" });
        }
    },
    registrationInProgress:false,
    registrationLastSubmitDate: null,
    register: function (onSuccess, onFailure) {
        try {
            if (this.registrationInProgress) {
                return;
            }
            
            this.registrationInProgress = true;
            this.registrationLastSubmitDate = new Date();


            if ($jq('#' + this.CountryCodeFieldname()).innerWidth() <= 0 && this.PostalCode() != null && this.PostalCode().length > 0) {
                if (this.PostalCode().length > 5) {
                    $jq('#' + this.CountryCodeFieldname()).val('CA');
                }
                else {
                    $jq('#' + this.CountryCodeFieldname()).val('US');
                }
            }

            var errors = this.validate();
            if (errors.length > 0) {
                this.registrationInProgress = false;
                onFailure(errors);
                return;
            }

            var username = this.Username();
            var password = this.Password();
            var emailAddress = this.EmailAddress();
            var countryCode = this.CountryCode();
            var postalCode = this.PostalCode();
            var city = this.City();
            var state = this.State();
            var gender = this.Gender();
            var genderSeek = this.GenderSeek();
            var birthDate = this.BirthDate();
            var surveyCode = this.SurveyAnswer();
            var adOptIn = this.AdOptIn();
            var emailGuid = this.EmailGUID();

            var url = PeopleMedia.CP.getPMApiBaseUrl("CreateMemberCPV2");
			var url1 = url+'/CreateMemberCPV2';
			
			url='';
            url += "&communityName=" + this.SiteId();
            url += "&username=" + username;
            url += "&password=" + password;
            url += "&emailAddress=" + emailAddress;
            url += "&countryCode=" + countryCode;
            url += "&postalCode=" + postalCode;
            url += "&city=" + city;
            url += "&state=" + state;
            url += "&gender=" + gender;
            url += "&birthDate=" + birthDate;
			var form_data={
				communityName: this.SiteId(),
				username: username,
				password: password,
				emailAddress: emailAddress,
				countryCode: countryCode,
				postalCode: postalCode,
				city: city,
				state: state,
				gender: gender,
				birthDate: birthDate,
			};
            if (PeopleMedia.CP.SearchID() != undefined && PeopleMedia.CP.SearchID() != null) {
                url += "&searchID=" + PeopleMedia.CP.SearchID();
				form_data.searchID = PeopleMedia.CP.SearchID();
            } else {
                url += "&searchID=999";
				form_data.searchID = 999;
            }
			
            url += "&affiliateID=" + PeopleMedia.CP.AffiliateID();
            url += "&sponsorID=" + PeopleMedia.CP.SponsorID();
            url += "&visitorID=" + PeopleMedia.CP.VisitorID();
            url += "&cpSessionID=" + PeopleMedia.CP.SessionId();
            url += "&signupForm=" + 106;
            url += "&surveyCode=" + surveyCode;
            url += "&adOptIn="+ adOptIn;
			form_data.affiliateID = PeopleMedia.CP.AffiliateID();
			form_data.sponsorID = PeopleMedia.CP.SponsorID();
			form_data.visitorID = PeopleMedia.CP.VisitorID();
			form_data.cpSessionID = PeopleMedia.CP.SessionId();
			form_data.signupForm = 106;
			form_data.surveyCode = surveyCode;
			form_data.adOptIn = adOptIn;
			
            if (typeof (emailGuid) !== 'undefined' && emailGuid !== null && emailGuid.length > 0) {
                url += "&emailGUID=" + emailGuid;
				form_data.emailGUID = emailGuid;
            }
            if (typeof(genderSeek) !== 'undefined' && genderSeek != null && genderSeek.length > 0 && typeof(PeopleMedia.CP.GenderSeekEnabled()) !== 'undefined' && PeopleMedia.CP.GenderSeekEnabled() != null && PeopleMedia.CP.GenderSeekEnabled()) {
                url += "&seeking=" + genderSeek;
				form_data.seeking = genderSeek;
            } else {
                url += "&seeking=0";
				form_data.seeking = 0;
            }
            url += "&callbackmethod=?";
			form_data.adOptIn = adOptIn;

            PeopleMedia.CP.ui_busy();

            var thisObj = this;
            var startTime = new Date().getTime();
            var timeoutValue = 60000;
            jQuery.ajax({
                type: "POST",
                url: url1,
                dataType: "json",
				data: form_data,
                success: function (data) {
                    thisObj.register_complete(onSuccess, onFailure, data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var endTime = new Date().getTime();
                    var duration = (endTime - startTime);
                    var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                    if (!data.IsCancelled) {
                    PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "register", duration: duration }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                    });
                    }
                    thisObj.register_complete(onSuccess, onFailure, data);
                },
                async: true,
                cache: false,
                timeout: timeoutValue
            });
        }
        catch (ex) {
            this.registrationInProgress = false;
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"register" });
        }
    },
    register_complete: function (onSuccess, onFailure, data) {
        try {
            this.registrationInProgress = false;
            var errors = [];
            PeopleMedia.CP.ui_done();
            if (data.Fault) {
                if (!data.Fault.IsCancelled) {
					for (var k in data.text) {
					  errors.push({ Field: '', Text: data.text[k] });
					}
                }
                onFailure(errors);
            } else {
                if (data.IsDuplicateEmailAddressOnSisterSite == true) {
                    errors.push({ "Code": "DuplicateEmailAddressOnSisterSite",
                        "Text": "DuplicateEmailAddressOnSisterSite",
                        "SisterSiteID": data.SisterSiteID,
                        "SisterSiteName": data.SisterSiteName
                    });
                    onFailure(errors);
                } else if (data.IsDuplicateEmailAddressUsernameAndPasswordOnSisterSite == true) {
                    errors.push({ "Code": "DuplicateEmailAddressUsernameAndPasswordOnSisterSite",
                        "Text": "DuplicateEmailAddressUsernameAndPasswordOnSisterSite",
                        "SisterSiteID": data.SisterSiteID,
                        "SisterSiteName": data.SisterSiteName
                    });
                    onFailure(errors);
                } else {
                    this._registrationData = data.CommunityMember;
					PeopleMedia.CP.MemberID(data.CommunityMember);
                    PeopleMedia.CP.Services.persistCookies(data);
                    this.incrementIsRegisteredLoginCounter();
                    onSuccess(data.CommunityMember);
                }
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"register_complete" });
        }
    },
    validate: function () {
        try {
            var errors = [];
            errors = errors.concat(this.validateUsername());
            errors = errors.concat(this.validatePassword());
            errors = errors.concat(this.validateEmailAddress());
            errors = errors.concat(this.validateCountryCode());
            errors = errors.concat(this.validatePostalCode());
            errors = errors.concat(this.validateGender());
            errors = errors.concat(this.validateBirthDay());
            errors = errors.concat(this.validateTermsAndConditions());
            if ($jq("#" + this.EmailAddressConfirmationFieldname()).length > 0) {
                errors = errors.concat(this.validateEmailAddressConfirmation());
            }
            return errors;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validate" });
            return [];
        }
    },
    validateUsername: function () {
        try {
            if (this.Username() == null || this.Username() == '') {
                return [{ Field: this.UsernameFieldname(), Text: PeopleMedia.CP.ClientMessages.RegHandle}];
            }
            return [];
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateUsername" });
            return [];
        }
    },
    validatePassword: function () {
        try {
            if (this.Password() == null || this.Password() == '') {
                return [{ Field: this.PasswordFieldname(), Text: PeopleMedia.CP.ClientMessages.LoginPassword}];
            }
            return [];
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validatePassword" });
            return [];
        }
    },
    validateUsernameAndPassword: function (onValidationComplete) {
        try {
            var errors = [];

            errors = this.validateUsername();
            errors = errors.concat(this.validatePassword());

            if (errors.length == 0 && onValidationComplete) {
                var url = PeopleMedia.CP.getPMApiBaseUrl("ValidateUsernameAndPassword");
                url += "&communityName=" + this.SiteId();
                url += "&username=" + encodeURIComponent(this.Username());
                url += "&password=" + encodeURIComponent(this.Password());
                url += "&callbackmethod=?";

                PeopleMedia.CP.ui_busy();

                var thisObj = this;
                var startTime = new Date().getTime();
                var timeoutValue = 30000;
                jQuery.ajax({
                    type: "GET",
                    url: url,
                    dataType: "json",
                    success: function (data, status, jqXHR) {
                        thisObj.validateUsernameAndPassword_complete(onValidationComplete, errors, data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var endTime = new Date().getTime();
                        var duration = (endTime - startTime);
                        var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                        if (!data.IsCancelled) {
                        PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "validateUsernameAndPassword", duration: duration }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                            });
                        }
                            thisObj.validateUsernameAndPassword_complete(onValidationComplete, errors, data);
                    },
                    async: true,
                    cache: false,
                    timeout: timeoutValue
                });
            } else {
                if (onValidationComplete) {
                    onValidationComplete(errors);
                }
            }

            return errors;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateUsernameAndPassword" });
            return [];
        }
    },
    validateUsernameAndPassword_complete: function (onValidationComplete, errors, data) {
        try {
            var errors = [];
            PeopleMedia.CP.ui_done();
            if (data.Fault) {
                if (!data.Fault.IsCancelled) {
                errors.push(PeopleMedia.CP.convertFaultToError(data.Fault, this.UsernameFieldname()));
                }
            } else if (data.IsValid != undefined && data.IsValid == false) {
                if (data.Reason) {
                    errors.push({ Field: this.UsernameFieldname(), Text: data.Reason });
                }
            }
            onValidationComplete(errors, data);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateUsernameAndPassword_complete" });
        }
    },
    validateEmailAddress: function () {
        try {
            if (this.EmailAddress() == null || this.EmailAddress() == '') {
                return [{ Field: this.EmailAddressFieldname(), Text: PeopleMedia.CP.ClientMessages.RegEmail}];
            }
            var regex = /^['_a-z0-9-]+(\.['_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.(([a-z]{2,3})|(aero|coop|info|museum|name))$/i;
            if (!regex.test(this.EmailAddress())) {
                return [{ Field: this.EmailAddressFieldname(), Text: "Please enter a valid email address."}];
            } else if (this.EmailAddress().length > 50) {
                return [{ Field: this.EmailAddressFieldname(), Text: "Please enter an email address less than 50 characters."}];
            }
            return [];
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateEmailAddress" });
            return [];
        }
    },
    checkCommonEmailMistakes: function () {
        try {
            if (typeof (PeopleMedia.CP.InvalidEmailDomainCheckEnabled()) !== 'undefined' && PeopleMedia.CP.InvalidEmailDomainCheckEnabled()) {

                var isBadEmail = false;
                this.OriginalEmailAddress = this.EmailAddress();
                var badAddresses = [
                    { id: 'aol.con', correct: 'aol.com' },
                    { id: '-aol.com', correct: 'aol.com' },
                    { id: 'comast.net', correct: 'comcast.net' },
                    { id: 'gmail.con', correct: 'gmail.com' },
                    { id: 'gmail.co', correct: 'gmail.com' },
                    { id: 'gmal.com', correct: 'gmail.com' },
                    { id: 'gmial.com', correct: 'gmail.com' },
                    { id: 'gmail.cim', correct: 'gmail.com' },
                    { id: 'ail.com', correct: 'gmail.com' },
                    { id: 'gmaill.com', correct: 'gmail.com' },
                    { id: 'gmail.com.com', correct: 'gmail.com' },
                    { id: '-gmail.com', correct: 'gmail.com' },
                    { id: 'hotmai.com', correct: 'hotmail.com' },
                    { id: 'hoymail.com', correct: 'hotmail.com' },
                    { id: 'hotmail.con', correct: 'hotmail.com' },
                    { id: 'hotmal.com', correct: 'hotmail.com' },
                    { id: 'homail.com', correct: 'hotmail.com' },
                    { id: 'hotmail.net', correct: 'hotmail.com' },
                    { id: 'hotmial.com', correct: 'hotmail.com' },
                    { id: 'otmail.com', correct: 'hotmail.com' },
                    { id: 'hotmaill.com', correct: 'hotmail.com' },
                    { id: 'HOTAIL.COM', correct: 'hotmail.com' },
                    { id: 'htomail.com', correct: 'hotmail.com' },
                    { id: 'hotmaol.com', correct: 'hotmail.com' },
                    { id: 'hotmail.com.com', correct: 'hotmail.com' },
                    { id: 'hotamil.com', correct: 'hotmail.com' },
                    { id: 'hotamail.com', correct: 'hotmail.com' },
                    { id: 'hotmeil.com', correct: 'hotmail.com' },
                    { id: 'holmail.com', correct: 'hotmail.com' },
                    { id: 'yahoo.co', correct: 'yahoo.com' },
                    { id: 'yahoo.con', correct: 'yahoo.com' },
                    { id: 'yahoo.cm', correct: 'yahoo.com' },
                    { id: 'yahoo.om', correct: 'yahoo.com' },
                    { id: 'tahoo.com', correct: 'yahoo.com' },
                    { id: 'yahoo.cpm', correct: 'yahoo.com' },
                    { id: 'yahoo.com.com', correct: 'yahoo.com' },
                    { id: 'yahhoo.com', correct: 'yahoo.com' },
                    { id: 'yahoo.cim', correct: 'yahoo.com' },
                    { id: '-ahoo.com', correct: 'yahoo.com' },
                ];

                var badAddress;
                var domain = this.EmailAddress().split('@');
                if (domain[1] != null) {
                    badAddress = badAddresses.filter(function (address) {
                        return address.id == domain[1].toLowerCase();
                    });
                    if (badAddress != undefined && badAddress != null && badAddress.length > 0) {
                        isBadEmail = true;
                    }
                }

                if (isBadEmail) {
                    //$jq("#" + this.EmailAddressFieldname()).val('Bad Email');
                    var correctAddress = domain[0] + "@" + badAddress[0].correct;
                    PeopleMedia.CP.Messaging.showEmailError([{ Field: this.EmailAddressFieldname(), Text: "Did you mean: " + correctAddress, Value: correctAddress }]);
                    var emailAddressFieldName = this.EmailAddressFieldname();
                    var originalEmailAddress = this.OriginalEmailAddress;
                    $jq('#correctEmailAddressChkBox').change(function () {
                        if ($jq('#correctEmailAddressChkBox').is(':checked')) {
                            $jq("#" + emailAddressFieldName).val(correctAddress);
                        } else {
                            $jq("#" + emailAddressFieldName).val(originalEmailAddress);
                        }
                    });
                }
            }

        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"checkCommonEmailMistakes" });
            return [];
        }
    },
    validateEmailAddressConfirmation: function () {
        try {
            if (this.EmailAddressConfirmation() != this.EmailAddress()) {
                return [{ Field: this.EmailAddressConfirmationFieldname(), Text: "Email addresses do not match."}];
            }
            return [];
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateEmailAddressConfirmation" });
            return [];
        }
    },
    validateCountryCode: function () {
        try {
            if (this.CountryCode() == null || this.CountryCode() == '') {
                return [{ Field: this.CountryCodeFieldname(), Text: PeopleMedia.CP.ClientMessages.RegCountryCode}];
            }
            return [];
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateCountryCode" });
            return [];
        }
    },
    validatePostalCode: function (onValidationComplete) {
        try {
            var errors = [];
            var countryCode = this.CountryCode();
            var postalCode = this.PostalCode();
            var city = this.City();
            var state = this.State();

            if (countryCode != 'US' && countryCode != 'CA') {
                postalCode = '';
            }

            if (countryCode == 'US' || countryCode == 'CA') {
                city = '';
                state = '';
                if (postalCode == null || postalCode == '') {
                    errors.push({ Field: this.PostalCodeFieldname(), Text: PeopleMedia.CP.ClientMessages.RegPostalcode });
                }
            }
            else if (countryCode != null && countryCode != '') {
                postalCode = '';
                if (city == null || city == '') {
                    errors.push({ Field: this.PostalCodeFieldname(), Text: PeopleMedia.CP.ClientMessages.RegCity });
                }
                if (state == null || state == '') {
                    errors.push({ Field: this.PostalCodeFieldname(), Text: PeopleMedia.CP.ClientMessages.RegState });
                }
            }

            if (errors.length == 0 && onValidationComplete && postalCode.length > 0) {
                var url = PeopleMedia.CP.getPMApiBaseUrl("ValidatePostalCode");
                url += "&communityName=" + this.SiteId();
                url += "&countryCode=" + countryCode;
                url += "&postalCode=" + postalCode;
                url += "&callbackmethod=?";

                PeopleMedia.CP.ui_busy();

                var thisObj = this;
                var startTime = new Date().getTime();
                var timeoutValue = 30000;
                jQuery.ajax({
                    type: "GET",
                    url: url,
                    dataType: "json",
                    success: function (data) { 
                        thisObj.validatePostalCode_complete(onValidationComplete, errors, data); 
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        var endTime = new Date().getTime();
                        var duration = (endTime - startTime);
                        var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                        if (!data.IsCancelled) {
                        PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "validatePostalCode", duration: duration }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                            });
                        }
                            thisObj.validatePostalCode_complete(onValidationComplete, errors, data);
                    },
                    async: true,
                    cache: false,
                    timeout: timeoutValue
                });
            } else {
                if (onValidationComplete) {
                    onValidationComplete(errors);
                }
            }

            return errors;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validatePostalCode" });
            return [];
        }
    },
    validatePostalCode_complete: function (onValidationComplete, errors, data) {
        try {
            var errors = [];
            PeopleMedia.CP.ui_done();
            if (data.Fault) {
                if (!data.Fault.IsCancelled) {
                errors.push(PeopleMedia.CP.convertFaultToError(data.Fault, this.PostalCodeFieldname()));
            }
            }
            onValidationComplete(errors);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validatePostalCode_complete" });
        }
    },
    validateGender: function () {
        try {
            if (this.Gender() == null || this.Gender() == '') {
                return [{ Field: this.GenderFieldname(), Text: PeopleMedia.CP.ClientMessages.RegGender}];
            }
            return [];
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateGender" });
            return [];
        }
    },
    validateBirthDay: function () {
        try {
            var errors = [];
            var birthMonth = this.BirthMonth();
            var birthDay = this.BirthDay();
            var birthYear = this.BirthYear();
            var birthDate = this.BirthDate();

            if (birthMonth == undefined || birthMonth == null || birthMonth == '' || birthMonth == '0') {
                errors.push({ Field: this.BirthMonthFieldname(), Text: PeopleMedia.CP.ClientMessages.RegBirthGeneric });
            } else if (birthDay == undefined || birthDay == null || birthDay == '' || birthDay == '0') {
                errors.push({ Field: this.BirthDayFieldname(), Text: PeopleMedia.CP.ClientMessages.RegBirthGeneric });
            } else if (birthYear == undefined || birthYear == null || birthYear == '' || birthYear == '0') {
                errors.push({ Field: this.BirthYearFieldname(), Text: PeopleMedia.CP.ClientMessages.RegBirthGeneric });
            } else if (birthDate == undefined || birthDate == null || birthDate == '') {
                errors.push({ Field: this.BirthMonthFieldname(), Text: PeopleMedia.CP.ClientMessages.RegBirthGeneric });
            } else if (!IsDateValid(birthYear, birthMonth, birthDay)) {
                errors.push({ Field: this.BirthDayFieldname(), Text: "The birth date entered is invalid. Please re-enter your birth date." });
            } else {						
                var today = new Date();
                var nowyear = today.getFullYear();
                
                var age = nowyear - birthYear;
                var nowmonth = today.getMonth();
                var nowday = today.getDate();
                var age_month = nowmonth - birthMonth;
                var age_day = nowday - birthDay;
                
                if (age < 18) {
                    errors.push({ Field: this.BirthDayFieldname(), Text: PeopleMedia.CP.ClientMessages.RegBirthUnder18  });
                } else if (age == 18 && age_month <= 0 && age_day < 0) {
                    errors.push({ Field: this.BirthDayFieldname(), Text: PeopleMedia.CP.ClientMessages.RegBirthUnder18  });				
                }
            }
            return errors;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateBirthDay" });
            return [];
        }
    },
    validateTermsAndConditions: function () {
        try {
            if (this.TermsAndConditions() == undefined || this.TermsAndConditions() == null || this.TermsAndConditions() == false) {
                return [{ Text: PeopleMedia.CP.ClientMessages.RegTermsAndConditions}];
            }
            return [];
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateTermsAndConditions" });
            return [];
        }
    },
    standardRegistrationProcess: function () {
        try {
            var thisObj = this;

            $jq("#" + this.RegistrationButtonFieldname()).fadeTo('fast', '0.3');
            this.register(
                function (data) {
                    thisObj.MemberId(data.Identifier);
                    var onRegistrationSuccess = thisObj.OnRegistrationSuccess();
                    if (onRegistrationSuccess == undefined || onRegistrationSuccess == null) {
                        onRegistrationSuccess = function () {
                            thisObj.standardOnRegistrationSuccess(thisObj, data);
                        };
                    }
                    onRegistrationSuccess(thisObj, data);
					$('#divLoginRegistration').hide();
					$('#divProfile').show();
                },
                function (errors) {
                    var onRegistrationFailure = thisObj.OnRegistrationFailure();
                    if (onRegistrationFailure == undefined || onRegistrationFailure == null) {
                        onRegistrationFailure = function () {
                            thisObj.standardOnRegistrationFailure(thisObj, errors);
                        };
                    }
                    onRegistrationFailure(thisObj, errors);
                }
            );
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"standardRegistrationProcess" });
        }
    },
    standardOnRegistrationSuccess: function (sender, data) {
        try {
            PeopleMedia.CP.gotoSite(data.AutoLoginUrl + "&evt=2");
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"standardOnRegistrationSuccess" });
        }
    },
    standardOnRegistrationFailure: function (sender, errors) {
        try {
            $jq("#" + this.RegistrationButtonFieldname()).fadeTo('fast', '1.0');
           
            PeopleMedia.CP.Messaging.show(errors);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"standardOnRegistrationFailure" });
        }
    },
    incrementIsRegisteredLoginCounter: function () {
        try {
            var counter = PeopleMedia.Net.readCookie('IsRegisteredLoginCounter');
            var loginCount = (counter != null) ? parseInt(counter, 10) : 0;
            if (isNaN(loginCount)) {
                loginCount = 0;
            }
            loginCount++;
            PeopleMedia.Net.createCookie('IsRegisteredLoginCounter', loginCount.toString());
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "incrementIsRegisteredLoginCounter" });
            return false;
        }
    },
    addCountrySelectCityStatePostalCodeSwap: function (countrySelectFieldname, postalCodeDivFieldname, cityStateDivFieldname) {
        try {
            var thisObj = this;
            $jq('#' + countrySelectFieldname).bind('change', function () {
                thisObj.showZipPostalCodeCityState();
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"addCountrySelectCityStatePostalCodeSwap" });
        }
    },
    loadBirthDateDropdowns: function () {
        try {
            if (this.BirthMonthFieldname() != undefined && this.BirthMonthFieldname() != null && $jq("#" + this.BirthMonthFieldname()).length > 0) {
                if ($jq("#" + this.BirthMonthFieldname())[0].length == 0) {
                    var months = [
                    { id: "0", name: "Month" }, { id: "1", name: "January" }, { id: "2", name: "February" }, { id: "3", name: "March" }, { id: "4", name: "April" },
                    { id: "5", name: "May" }, { id: "6", name: "June" }, { id: "7", name: "July" }, { id: "8", name: "August" }, { id: "9", name: "September" },
                    { id: "10", name: "October" }, { id: "11", name: "November" }, { id: "12", name: "December"}];
                    PeopleMedia.UI.loadDDL(this.BirthMonthFieldname(), months, "id", "name");
                }
            }

            if (this.BirthDayFieldname() != undefined && this.BirthDayFieldname() != null && $jq("#" + this.BirthDayFieldname()).length > 0) {
                if ($jq("#" + this.BirthDayFieldname())[0].length == 0) {
                    var months = [{ id: "0", name: "Day"}];
                    for (var i = 1; i <= 31; ++i) {
                        months[i] = { id: i.toString(), name: i.toString() };
                    }
                    PeopleMedia.UI.loadDDL(this.BirthDayFieldname(), months, "id", "name");
                }
            }

            if (this.BirthYearFieldname() != undefined && this.BirthYearFieldname() != null && $jq("#" + this.BirthYearFieldname()).length > 0) {
                if ($jq("#" + this.BirthYearFieldname())[0].length > 0) {
                    $jq("#" + this.BirthYearFieldname() + " >option").remove();
                }
                var maxYear = (new Date()).getFullYear();
                var minYear = (new Date()).getFullYear() - 120 < 1900 ? 1900 : (new Date()).getFullYear() - 120;
                var years = [{ id: "0", name: "Year"}];
                for (var i = minYear; i <= maxYear; ++i) {
                    years[i - minYear + 1] = { id: i.toString(), name: i.toString() };
                }
                PeopleMedia.UI.loadDDL(this.BirthYearFieldname(), years, "id", "name");
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"loadBirthDateDropdowns" });
        }
    },
    loadQuestions: function () {
        try {
            var thisObj = this;
            this._questions = [
                {
                    "QuestionID": 991, "QuestionText": "Country", "Validator": function (onValidationComplete) {
                        var errors = thisObj.validateCountryCode();
                        if (onValidationComplete) {
                            onValidationComplete(errors);
                        }
                        return errors;
                    }
                },
                {
                    "QuestionID": 992, "QuestionText": "PostalCode", "Validator": function (onValidationComplete) {
                        var errors = thisObj.validatePostalCode(onValidationComplete);
                        return errors;
                    }
                },
                {
                    "QuestionID": 993, "QuestionText": "BirthDate", "Validator": function (onValidationComplete) {
                        var errors = thisObj.validateBirthDay();
                        if (onValidationComplete) {
                            onValidationComplete(errors);
                        }
                        return errors;
                    }
                },
                {
                    "QuestionID": 994, "QuestionText": "Username & Password", "Validator": function (onValidationComplete) {
                        var errors = thisObj.validateUsernameAndPassword(onValidationComplete);
                        return errors;
                    }
                },
                {
                    "QuestionID": 995, "QuestionText": "Email&TC", "Validator": function (onValidationComplete) {
                        var errors = thisObj.validateEmailAddress().concat(thisObj.validateEmailAddressConfirmation().concat(thisObj.validateTermsAndConditions()));
                        if (onValidationComplete) {
                            onValidationComplete(errors);
                        }
                        return errors;
                    }
                }
            ];
            //this._panelCount = this._questions.length;
            this.showPanel(1);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"loadQuestions" });
        }
    },
    fireOnQuestionDisplay: function () {
        try {
            if (this._onQuestionDisplay != undefined && this._onQuestionDisplay != null) {
                this._onQuestionDisplay();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"fireOnQuestionDisplay" });
        }
    },
    showNextPanel: function () {
        try {
            var thisObj = this;
            if ($jq("#divRegistrationUsernameTaken:visible").length > 0) {
                var newUsername = $jq("input[name=selected_username]:checked").val();
                if (newUsername == undefined || newUsername == null || newUsername.length <= 0) {
                    newUsername = $jq("#txtRegistrationNewUsername").val();
                }
                $jq("#" + this.UsernameFieldname()).val(newUsername);
                this.validateCurrentQuestion(function () {
                    PeopleMedia.CP.Messaging.reset();
                    thisObj.processRegistration();
                });
            }
            else if (this._currentPanelNumber < this._panelCount) {
                this.validateCurrentQuestion(function () {
                    ++thisObj._currentPanelNumber;
                    PeopleMedia.CP.Messaging.reset();
                    thisObj.showPanel(thisObj._currentPanelNumber);
                });
            }
            else {
                this.validateCurrentQuestion(function () {
                    PeopleMedia.CP.Messaging.reset();
                    thisObj.processRegistration();
                });
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showNextPanel" });
        }
    },
    showPreviousPanel: function () {
        try {
            if (this._currentPanelNumber > 1) {
                --this._currentPanelNumber;
                PeopleMedia.CP.Messaging.reset();
                this.showPanel(this._currentPanelNumber);
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showPreviousPanel" });
        }
    },
    showPanel: function (panelNum) {
        try {
            if ($jq('#divRegistrationQuestions_' + panelNum.toString()).length > 0) {
                this.hideAllPanels();
                $jq('#divRegistrationQuestions_' + panelNum.toString()).show();
                this.fireOnQuestionDisplay();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showPanel" });
        }
    },
    hideAllPanels: function () {
        try {
            for (var i = 1; i <= this._panelCount; ++i) {
                if ($jq('#divRegistrationQuestions_' + i.toString()).length > 0) {
                    $jq('#divRegistrationQuestions_' + i.toString()).hide();
                }
            }
            $jq("#divRegistrationUsernameTaken").hide();
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"hideAllPanels" });
        }
    },
    updateZipPostalCodeLabel: function () {
        try {
            var countrySelectName = this.CountryCodeFieldname();
            var zipCodeDisplay = 'none';
            var postalCodeDisplay = '';
            var countryCode = $jq('#' + countrySelectName).val();
            if (countryCode != null && countryCode.toLowerCase() == 'us') {
                zipCodeDisplay = '';
                postalCodeDisplay = 'none';
            }
            $jq('.cssRegistrationZipCodeDisplay').each(function () {
                $jq(this).css('display', zipCodeDisplay);
            });
            $jq('.cssRegistrationPostalCodeDisplay').each(function () {
                $jq(this).css('display', postalCodeDisplay);
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"updateZipPostalCodeLabel" });
        }
    },
    showZipPostalCodeCityState: function () {
        try {
            var thisObj = this;
            var countryCode = $jq('#' + this.CountryCodeFieldname()).val();
            if (countryCode == 'US' || countryCode == 'CA') {
                $jq('#' + this.CityStateDivFieldname()).fadeOut('fast', function () { $jq('#' + thisObj.PostalCodeDivFieldname()).fadeIn(); });
            } else {
                $jq('#' + this.PostalCodeDivFieldname()).fadeOut('fast', function () { $jq('#' + thisObj.CityStateDivFieldname()).fadeIn(); });
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"showZipPostalCodeCityState" });
        }
    },
    validateCurrentQuestion: function (onValidationSuccess, onValidationFailure) {
        try {
            var thisObj = this;
            var panelIndex = this._currentPanelNumber - 1;
            var currentQuestion = this._questions[panelIndex];
            var validator = (typeof(currentQuestion) !== 'undefined' && currentQuestion != null) ? currentQuestion.Validator : null;
            if (validator != undefined && validator != null) {
                validator(function (errors, validationData) {
                    if (errors != undefined && errors != null && errors.length > 0) {
                        if (thisObj.isUsernameTakenValidationError(validationData)) {
                            //thisObj.handleUsernameTakenValidationError(validationData);
                            // skip username taken error at this point... need to wait until last page
                            onValidationSuccess();
                        } else {
                            if (onValidationFailure) {
                                onValidationFailure(errors);
                            } else {
                                PeopleMedia.CP.Messaging.show(errors);
                            }
                        }
                    } else {
                        onValidationSuccess();
                    }
                });
            } else {
                onValidationSuccess();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validateCurrentQuestion" });
        }
    },
    isValidationErrorWithCodeName: function (codeName, validationData) {
        try {
            return validationData && validationData.Code && validationData.Code == codeName;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"isValidationErrorWithCodeName" });
            return true;
        }
    },
    isUsernameTakenValidationError: function (validationData) {
        try {
            return this.isValidationErrorWithCodeName("UsernameTaken", validationData) && validationData.AlternativeUsernames && validationData.AlternativeUsernames.length > 0;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"isUsernameTakenValidationError" });
            return true;
        }
    }
};
